import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:xingsu/util/alert_dialog.dart';
import 'package:xingsu/widget/hud.dart';

class PublishViewModel extends GetxController {
  final TextEditingController titleController = TextEditingController();
  final TextEditingController descController = TextEditingController();

  final coverPath = "".obs;

  @override
  void onInit() {
    super.onInit();
  }

  void chooseVideo() async {
    final status = await Permission.photos.request();

    if (status.isGranted) {
      final ImagePicker _picker = ImagePicker();

      final XFile? image = await _picker.pickVideo(source: ImageSource.gallery);
      if (image == null) return;
      VideoThumbnail.thumbnailFile(
              video: image.path,
              imageFormat: ImageFormat.PNG,
              maxWidth: 128,
              quality: 25)
          .then((value) {
        if (value == null) return;
        coverPath.value = value;
      });
    } else {
      showCupertinoAlertDialog(
          title: "提示",
          desc: "你未开启相册权限请前往开启",
          okClickCallback: () {
            openAppSettings();
          });
      return;
    }
  }

  void chooseCover() async {
    final ImagePicker _picker = ImagePicker();
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image == null) return;
    coverPath.value = image.path;
  }

  void publish() {
    if (coverPath.isEmpty) {
      Fluttertoast.showToast(msg: "视频不能为空");
      return;
    }

    if (titleController.text.isEmpty) {
      Fluttertoast.showToast(msg: "标题不能为空");
      return;
    }

    HUD.show();
    Future.delayed(const Duration(seconds: 3), () {
      Fluttertoast.showToast(msg: "发布成功，待审核");
      HUD.hide();
      Get.back();
    });
  }
}
